package Solution151_175;

import java.util.HashMap;
import java.util.Map;

public class Solution167两数之和 {
    public int[] twoSum1(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] result = new int[2];
        for (int i = 0; i < numbers.length; i++) {
            if(map.containsKey(numbers[i])){
                result[0]=map.get(numbers[i]);
                result[1]=i+1;
                break;
            }
            map.put(target-numbers[i],i+1);
        }

        return result;
    }

    /**
     * 优解
     * @jieparam nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        int i = 0,j = nums.length - 1;
        int ans[] = new int[2];
        while(i < j){
            int sum = nums[i] + nums[j];
            if(sum < target){
                i++;
            }else if(sum > target){
                j--;
            }else{
                ans[0] = i + 1;
                ans[1] = j + 1;
                break;
            }
        }

        return ans;
    }
}
